package com.wujian.love.study.thread;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @ClassName: SemaphoreTest
 * @Description: 信号量代码测试
 * @Author: wuj
 * @Date: 2021-03-08 17:00
 **/
public class SemaphoreTest {

    //饭店里面有10个座位
    private  static  Semaphore semaphore=new Semaphore(2,true);

    public static void main(String[] args) {

        //模拟100个人来吃饭
        for(int i=0;i<5;i++){
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("===="+Thread.currentThread().getName()+"来到饭店");
                        //返回可用的令牌数量
                        int seat = semaphore.availablePermits();
                        if(seat ==0 ){
                            System.out.println("座位不足，请耐心等待");
                        }
                        //获取令牌尝试进入饭店
                        semaphore.acquire();

                        System.out.println(Thread.currentThread().getName()+"成功进入饭店");
                        //模拟吃饭时间
                        Thread.sleep(new Random().nextInt(10000));

                        System.out.println(Thread.currentThread().getName()+"离开饭店");
                        //释放令牌，腾出座位
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },i+"号客人");

            thread.start();

        }

    }
}
